package com.aaa.member.config;

import com.aaa.member.util.MyRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @fileName:ShiroConfig
 * @description:
 * @author:忆尘
 * @createTime:2020/11/13 18:52
 * @version:1.0.0
 */
@Configuration
public class ShiroConfig {

    /**
     * 初始化shiro过滤工厂类
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置未认证的地址访问后跳转的路径
        //shiroFilterFactoryBean.setLoginUrl("/html/login.html");
        //设置认证成功之后的跳转的路径
        //shiroFilterFactoryBean.setSuccessUrl("");
        //设置未授权的跳转的url
        //shiroFilterFactoryBean.setUnauthorizedUrl("");

        //不能使用hashMap 因为无序 linkMap有序
        Map<String,String> filterMap = new LinkedHashMap<>();
        //放行的
        /*filterMap.put("/ms/news/**","anon");
        filterMap.put("/cs/carController/**","anon");
        filterMap.put("/SsoController/userLogin","anon");
        filterMap.put("/sso/SsoController/userLogin","anon");*/
        //拦截的
        filterMap.put("/**","anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        //安全管理器 拦截到的东西交给安全管理器处理
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        return shiroFilterFactoryBean;
    }

    /**
     * 初始化安全管理器
     */
    @Bean
    public SecurityManager securityManager(){
        //实例化安全管理器
        DefaultWebSecurityManager securityManager =
                new DefaultWebSecurityManager();
        //设置个ream
        securityManager.setRealm(myRealm());
        return securityManager;
    }

    /**
     * 实例化Realm（安全数据的链接桥梁）
     * @return
     */
    @Bean
    public MyRealm myRealm(){
        //实例化myrealm
        MyRealm myRealm = new MyRealm();
        //校验匹配器
        myRealm.setCredentialsMatcher(credentialsMatcher());
        return myRealm;
    }


    /**
     * 加密算法及类型设置类
     * @return
     */
    @Bean
    public CredentialsMatcher credentialsMatcher(){
        //实例化
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法
        credentialsMatcher.setHashAlgorithmName("SHA-512");
        //设置hash次数
        credentialsMatcher.setHashIterations(1024);

        return credentialsMatcher;
    }


}
